package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.DateUtils;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.gateway.modules.ofs.entity.AppFilesEntity;
import cn.conac.rc.gateway.modules.ofs.entity.ApprovalEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.service.AppFilesService;
import cn.conac.rc.gateway.modules.ofs.service.ApprovalService;
import cn.conac.rc.gateway.modules.ofs.service.OrgStatusService;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="ofs/")
@Api(tags="部门的批文", description="三定信息")
public class ApprovalController {

    @Autowired
    ApprovalService approvalService;
    
    @Autowired 
    AppFilesService  appFilesService;
    
    @Autowired
    OrgStatusService  orgStatusService;

    @ApiOperation(value = "根据id取得批文信息", httpMethod = "GET", response = JSONObject.class, notes = "根据id取得批文信息")
    @RequestMapping(value = "bases/{id}/approvals", method = RequestMethod.GET)
    public JSONObject findApprovalById(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "id", required = true) @PathVariable("id") String id)
            throws RestClientException, Exception {
        return approvalService.appDetail(id);
    }

    @ApiOperation(value = "根据orgId取得批文信息列表", httpMethod = "GET", response = JSONObject.class, notes = "根据主表的orgId获取对应的批文信息列表")
    @RequestMapping(value = "orgs/{orgId}/approvals", method = RequestMethod.GET)
    public JSONObject findApprovalList(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId)
            throws RestClientException, Exception {
        return approvalService.appList(orgId);
    }

    @ApiOperation(value = "根据orgId获取主批文信息列表", httpMethod = "GET", response = JSONObject.class, notes = "根据主表的orgId获取对应的主批文信息列表")
    @RequestMapping(value = "orgs/{orgId}/mainApprovals", method = RequestMethod.GET)
    public JSONObject findMainApproval(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId)
            throws RestClientException, Exception {
        return approvalService.appMainList(orgId);
    }
    
    @ApiOperation(value = "部门批文信息保存", httpMethod = "POST", response = JSONObject.class, notes = "部门批文信息保存")
    @RequestMapping(value = "approvals/c", method = RequestMethod.POST)
    public Object cudApprovalSave(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门批文信息、批文文件信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 Map<String,String> idMap = new HashMap<String, String>();

    	 //******************第一步从页面侧获取部门批文信息和部门状态实体对象***********
         // 获得部门批文信息
    	 ApprovalEntity approvalEntityInfo = new ApprovalEntity();
    	 BeanMapper.copy(entityMap.get("approvalEntity"), approvalEntityInfo);
    	
    	 // 确保部门批文信息中的ID不为null
    	 String approvalId = approvalEntityInfo.getId();
    	 if(null == approvalId){
    		 //部门批文信息中的ID为null场合返回错误信息
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ the id of approvalEntityInfo is null] in function of approvalSave " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 // 获得部门批文文件信息
    	 AppFilesEntity appFilesEntityInfo = new AppFilesEntity();
    	 BeanMapper.copy(entityMap.get("appFilesEntity"), appFilesEntityInfo);
    	 
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
        
         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType = stepMask.substring(1, 2);
         }
         
         //******************第二步保存部门批文信息表**************************************
         // 执行保存部门批文信息表
    	 JSONObject approvalInfoJson =  approvalService.saveOrUpdate(submitType,approvalEntityInfo);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(approvalInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", approvalInfoJson.getJSONObject("result").getString("id"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(approvalInfoJson.getString("code"));
        	  resultInfo.setMsg("[approvalService.saveOrUpdate] in function of approvalSave " 
        			  					+ ResultPojo.MSG_FAILURE + "【"  + approvalInfoJson.getString("msg") + "】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	  //******************第三步保存部门批文文件信息表**************************************
          // 执行保存部门批文信息表
    	  appFilesEntityInfo.setBaseId(idMap.get("id"));
     	 JSONObject appFilesInfoJson =  appFilesService.saveOrUpdate(appFilesEntityInfo, submitType);
     	 // 判断保存是否成功失败
     	  if (ResultPojo.CODE_SUCCESS.equals(appFilesInfoJson.getString("code"))) {
     		  // 保存成功场合
     		 resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			 resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
           } else {
         	 // 保存失败场合
        	 // 程序事务控制
 		  	 // 删除保存的部门基本信息 TODO
         	  resultInfo.setCode(appFilesInfoJson.getString("code"));
         	  resultInfo.setMsg("[appFilesService.saveOrUpdate] in function of approvalSave " 
         			  					+ ResultPojo.MSG_FAILURE + "【"  + appFilesInfoJson.getString("msg") + "】");
         	  resultInfo.setResult(null);
          	  return resultInfo;
           }
    	  
    	 //*******************第四步保存部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("id"));
    	  // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.saveOrUpdate] in function of approvalSave " + ResultPojo.MSG_FAILURE + "【"  + statusInfoJson.getString("msg") + "】");
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }
    
    @ApiOperation(value = "部门批文信息更新", httpMethod = "POST", response = JSONObject.class, notes = "部门批文信息更新")
    @RequestMapping(value = "approvals/{baseId}/u", method = RequestMethod.POST)
    public Object cudApprovalUpdate(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("部门基本信息Id") @PathVariable("baseId") String baseId,
            @ApiParam(value = "部门批文信息、批文文件信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == baseId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ baseId of parameter is null ] in function of approvalUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	 //******************第一步从页面侧获取部门批文信息和部门状态实体对象***********
         // 获得部门批文信息
    	 ApprovalEntity approvalEntityInfo = new ApprovalEntity();
    	 BeanMapper.copy(entityMap.get("approvalEntity"), approvalEntityInfo);
    	
    	 // 确保部门批文信息中的ID不为null
    	 approvalEntityInfo.setId(baseId);
    	 
    	 // 获得部门批文文件信息
    	 AppFilesEntity appFilesEntityInfo = new AppFilesEntity();
    	 BeanMapper.copy(entityMap.get("appFilesEntity"), appFilesEntityInfo);
    	 
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
       
         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType = stepMask.substring(1, 2);
         }
         
         //******************第二步保存部门批文信息表**************************************
         // 执行保存部门批文信息表
    	 JSONObject approvalInfoJson =  approvalService.saveOrUpdate(submitType,approvalEntityInfo);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(approvalInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", approvalInfoJson.getJSONObject("result").getString("id"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(approvalInfoJson.getString("code"));
        	  resultInfo.setMsg("[approvalService.saveOrUpdate] in function of approvalUpdate " + 
        			  						ResultPojo.MSG_FAILURE + "【"  + approvalInfoJson.getString("msg") + "】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	  //******************第三步保存部门批文文件信息表**************************************
          // 执行保存部门批文信息表
    	  appFilesEntityInfo.setBaseId(idMap.get("id"));
     	 JSONObject appFilesInfoJson =  appFilesService.saveOrUpdate(appFilesEntityInfo, submitType);
     	 // 判断保存是否成功失败
     	  if (ResultPojo.CODE_SUCCESS.equals(appFilesInfoJson.getString("code"))) {
     		  // 保存成功场合
     		 resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			 resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
           } else {
         	 // 保存失败场合
        	 // 程序事务控制
 		  	 // 删除保存的部门基本信息 TODO
         	  resultInfo.setCode(appFilesInfoJson.getString("code"));
         	  resultInfo.setMsg("[appFilesService.saveOrUpdate] in function of approvalUpdate " + ResultPojo.MSG_FAILURE +"【"  + appFilesInfoJson.getString("msg") + "】");
         	  resultInfo.setResult(null);
          	  return resultInfo;
           }
    	  
    	 //*******************第四步保存部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("id"));
    	  // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.saveOrUpdate] in function of approvalUpdate " 
					  						+ ResultPojo.MSG_FAILURE + "【"   + statusInfoJson.getString("msg") + "】");
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }

    @ApiOperation(value = "三定查询之批文查询", httpMethod = "POST", response = JSONObject.class, notes = "根据查询条件获取三定批文信息列表(批文查询)")
    @RequestMapping(value = "/orgsApps", method = RequestMethod.POST)
    public JSONObject ofsApprovalList(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "查询条件", required = true) @RequestBody JSONObject approvalVo)
            throws RestClientException, Exception {
        return approvalService.ofsApprovalList(approvalVo);
    }
    
    @ApiOperation(value = "部门管理批文时间校验", httpMethod = "GET", response = JSONObject.class, notes = "校验新添加批文时间是否在新建部门批文时间之后")
    @RequestMapping(value = "approvals/{orgId}/check/after/{newAppDate}", method = RequestMethod.GET)
    public JSONObject checkAppDateAfter(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId,
            @ApiParam(value = "newAppDate", required = true) @PathVariable("newAppDate") String newAppDate)
            throws RestClientException, Exception {
    	ResultPojo resultInfo = new ResultPojo();
    	String newAppDateyyMMdd = DateUtils.formatTimeStamp(newAppDate);
    	if( null == newAppDateyyMMdd) {
    		 // 时间格式转换
			  resultInfo.setCode(ResultPojo.CODE_FAILURE);
			  resultInfo.setMsg(ResultPojo.MSG_FAILURE  + " 时间戳格式转换yyMMdd格式转换失败(函数：checkAppDateAfter)。“ +  ”参数为 ：" + newAppDate );
			  resultInfo.setResult(null);
    	}
        return approvalService.checkAppDateAfter(orgId, newAppDateyyMMdd);
    }
    
    @ApiOperation(value = "历史沿革批文时间校验", httpMethod = "GET", response = JSONObject.class, notes = "校验新添加批文时间是否在新建部门批文时间之前")
    @RequestMapping(value = "approvals/{orgId}/check/before/{newAppDate}", method = RequestMethod.GET)
    public JSONObject checkAppDateBefore(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId,
            @ApiParam(value = "newAppDate", required = true) @PathVariable("newAppDate") String newAppDate)
            throws RestClientException, Exception {
    	ResultPojo resultInfo = new ResultPojo();
    	String newAppDateyyMMdd = DateUtils.formatTimeStamp(newAppDate);
    	if( null == newAppDateyyMMdd) {
   		 // 时间格式转换
			  resultInfo.setCode(ResultPojo.CODE_FAILURE);
			  resultInfo.setMsg(ResultPojo.MSG_FAILURE  + " 时间戳格式转换yyMMdd格式转换失败(函数：checkAppDateBefore)。“ +  ”参数为 ：" + newAppDate );
			  resultInfo.setResult(null);
   	}
        return approvalService.checkAppDateBefore(orgId, newAppDateyyMMdd);
    }
    
}
